<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 产品分类 -->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="productsName"
            placeholder="请输入产品名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="productsOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!-- 产品信息 -->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="75px"
        >
          <el-form-item label="产品SKU" prop="sku">
            <el-input
              v-model="queryParams.sku"
              placeholder="请输入产品SKU"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="商品名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="是否配对供应商"
            prop="pairedSupplier"
            label-width="100"
          >
            <el-select
              v-model="queryParams.pairedSupplier"
              placeholder="请选择配对状态"
              clearable
            >
              <el-option label="未配对" value="0" />
              <el-option label="已配对" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
            <!-- 隐藏的文件选择按钮 -->
            <input
              type="file"
              ref="productFileInput"
              style="display: none"
              accept=".xlsx"
              @change="handleProductFileUpload"
            />
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['commodity:products:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['commodity:products:edit']"
              >修改</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['commodity:products:remove']">删除</el-button>
          </el-col> -->
          <!-- 修改导航栏中的删除按钮为停用按钮 -->
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-close"
              size="mini"
              :disabled="multiple"
              @click="handleDisable"
              v-hasPermi="['commodity:products:disable']"
              >停用</el-button
            >
          </el-col>
          <!-- 增加启用按钮，只有具有启用权限的人才看到 -->
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-check"
              size="mini"
              :disabled="multiple"
              @click="handleEnable"
              v-hasPermi="['commodity:products:enable']"
              >启用</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-folder-checked"
              size="mini"
              :disabled="multiple"
              @click="handleQueryCode"
              v-hasPermi="['commodity:products:remove']"
              >本地产品条码</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['commodity:products:export']"
              >导出</el-button
            >
          </el-col>
          <!-- 新增“组合”按钮：只有当选中产品数量>=2时才可点击 -->
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-s-operation"
              size="mini"
              :disabled="QRCode.length < 2"
              @click="handleCombine"
              v-hasPermi="['commodity:products:combine']"
              >组合</el-button
            >
          </el-col>
          <!-- 添加变体按钮 -->
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-crop"
              size="mini"
              :disabled="single"
              @click="handleVariant"
              v-hasPermi="['commodity:products:variant']"
            >
              变体
            </el-button>
          </el-col>
          <!-- 触发文件选择的按钮 -->
          <el-col :span="1.5">
            <el-button
              type="primary"
              size="mini"
              plain
              @click="triggerProductFileInput"
              v-hasPermi="['commodity:products:importProduct']"
            >
              导入产品表格
            </el-button>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="productsList"
          row-key="id"
          ref="table"
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <el-table-column
            type="selection"
            width="50"
            align="center"
            fixed="left"
            :reserve-selection="true"
          />
          <!-- <el-table-column label="图片" prop="imgName" align="center">
            <template slot-scope="scope">
              <div class="image-container">
                <image-preview v-for="(image, index) in scope.row.imgName" :key="index" :src="image" :width="50"
                  :height="50" class="image-item" />
              </div>
            </template>
          </el-table-column> -->
          <el-table-column
            label="图片"
            prop="imgName"
            align="center"
            min-width="200"
          >
            <template slot-scope="scope">
              <div class="image-container">
                <image-preview
                  v-for="(image, index) in scope.row.imgName"
                  :key="index"
                  :src="image"
                  :width="50"
                  :height="50"
                  class="image-item"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="编号 "
            align="center"
            prop="proNo"
            min-width="90"
          />
          <!-- <el-table-column label="名称" align="center" prop="name" min-width="300">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.name" placement="top">
                <span v-if="scope.row.name">
                  {{ scope.row.name.slice(0, 10) }}
                  <span v-if="scope.row.name.length > 10">...</span>
                </span>
              </el-tooltip>
            </template>
          </el-table-column> -->
          <el-table-column
            label="名称"
            align="center"
            prop="name"
            min-width="400"
          />
          <el-table-column
            label="品牌"
            align="center"
            prop="brandName"
            min-width="120"
          />
          <el-table-column
            label="产品SKU"
            align="center"
            prop="sku"
            min-width="450"
          />
          <el-table-column
            label="状态"
            prop="status"
            align="center"
            min-width="120"
            fixed="right"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_normal_disable"
                :value="scope.row.status"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="交货周期(天)"
            align="center"
            prop="leadTime"
            min-width="120"
          />
          <el-table-column
            label="单价(￥)"
            align="center"
            prop="price"
            min-width="120"
          />
          <el-table-column
            label="单品尺寸(mm)"
            align="center"
            prop="size"
            width="110px"
            min-width="120"
          />
          <el-table-column
            label="产品重量(kg)"
            align="center"
            prop="productWeight"
            min-width="120"
          />
          <el-table-column
            label="发布时间"
            align="center"
            prop="addTime"
            min-width="120"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.addTime, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="产品描述"
            align="center"
            prop="desc"
            min-width="120"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.desc">
                {{ scope.row.desc.slice(0, 10) }}
                <span v-if="scope.row.desc.length > 10">...</span>
              </span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="120"
            fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['commodity:products:edit']">修改</el-button>

              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['commodity:products:remove']">删除</el-button>
            </template>
          </el-table-column> -->
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            min-width="120"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-dropdown
                trigger="click"
                @command="handleCommand(scope.row, $event)"
              >
                <el-button type="text" size="mini">
                  操作 <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    command="handleUpdate"
                    v-hasPermi="['commodity:products:edit']"
                    >修改产品信息</el-dropdown-item
                  >
                  <el-dropdown-item
                    command="view"
                    v-hasPermi="['commodity:products:query']"
                    >查看产品信息</el-dropdown-item
                  >
                  <el-dropdown-item
                    command="handleView"
                    v-hasPermi="['commodity:products:walmartView']"
                    >查看walmart配对信息</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改产品管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="900px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="产品管理" name="first">
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品编号" prop="proNo">
                  <el-input
                    v-model="form.proNo"
                    placeholder="系统自动生成商品编号"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品名称" prop="name">
                  <el-input
                    v-model="form.name"
                    placeholder="请输入商品名称"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品SKU" prop="sku">
                  <el-input
                    v-model="form.sku"
                    placeholder="请输入产品SKU"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="名称" prop="names">
                  <el-input
                    v-model="form.names"
                    ref="firstTabFirstInput"
                    placeholder="请输入名称"
                    @input="autoFillModel"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <!-- 当为组合产品时，新增“组合产品明细”输入区域 -->
              <el-form-item
                v-if="isCombination"
                label="组合产品明细"
                prop="comboDetails"
              >
                <div
                  v-for="(item, index) in selectedProductsForCombo"
                  :key="item.id"
                  style="margin-bottom: 5px"
                >
                  <span>{{ item.sku }} 数量：</span>
                  <el-input
                    v-model.number="item.comboQty"
                    type="number"
                    min="1"
                    placeholder="请输入数量"
                    style="width: 100px"
                  ></el-input>
                </div>
              </el-form-item>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品类型 " prop="catesId">
                  <treeselect
                    v-model="form.catesId"
                    noOptionsText="暂无数据"
                    :options="processedProductsOptions"
                    :show-count="true"
                    placeholder="请选择父商品分类"
                    :disable-branch-nodes="false"
                    :disabled="!form.brandId"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="品牌" prop="brandId">
                  <treeselect
                    v-model="form.brandId"
                    :options="brandList"
                    :show-count="true"
                    @select="handleChange"
                    @input="autoFillModel"
                    placeholder="请选择父品牌分类"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="OEM" prop="oem">
                  <treeselect
                    v-model="form.oem"
                    noOptionsText="暂无数据"
                    :options="processedOemOptions"
                    :show-count="true"
                    placeholder="请选择OEM"
                    :disabled="!form.brandId || !this.insertUpdate"
                    @input="autoFillOEM"
                    :disable-branch-nodes="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="规格型号" prop="model">
                  <el-input
                    v-model="form.model"
                    placeholder="请输入商品规格型号"
                    @input="autoFillModel"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio
                      v-for="(dict, index) in dict.type.sys_normal_disable"
                      :key="index"
                      :label="dict.value"
                    >
                      {{ dict.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序" prop="sort">
                  <el-input-number
                    v-model="form.sort"
                    controls-position="right"
                    :min="1"
                    :max="100000"
                  ></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="属性" prop="attributes">
                  <el-select
                    v-model="form.attributes"
                    placeholder="请选择属性"
                    clearable
                    multiple
                  >
                    <el-option
                      v-for="(dict, index) in dict.type.sys_product_attribute"
                      :key="index"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="包装清单" prop="packingList">
                  <el-input
                    v-model="form.packingList"
                    type="textarea"
                    placeholder="请输入包装清单"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="产品描述" prop="desc">
                  <el-input
                    v-model="form.desc"
                    type="textarea"
                    placeholder="请输入产品描述"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="产品链接" prop="productUrl">
                  <el-input
                    v-model="form.productUrl"
                    type="textarea"
                    placeholder="请输入产品链接"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 原来的备注输入框，修改为包含图片上传 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="productRemarks">
                  <div class="textarea-container">
                    <el-input
                      v-model="form.productRemarks"
                      type="textarea"
                      placeholder="请输入备注"
                      :rows="4"
                    />
                    <!-- 图片上传组件放在textarea底部 -->
                    <div class="upload-section">
                      <image-upload
                        ref="remarkImageUpload"
                        :auto-upload="false"
                        v-model="form.productRemarksImgName"
                        :limit="5"
                      />
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="15">
                <el-form-item label="产品图片" prop="imgName">
                  <image-upload
                    ref="productImageUpload"
                    :auto-upload="false"
                    v-model="form.imgName"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="信息管理" name="second">
            <el-row>
              <el-col :span="12">
                <el-form-item label="单品尺寸" prop="size">
                  <span slot="label"
                    >单品尺寸
                    <el-tooltip class="item" effect="dark" placement="right">
                      <div slot="content">裸机尺寸</div>
                      <i class="el-icon-warning-outline"></i>
                    </el-tooltip>
                  </span>
                  <el-input
                    v-model="form.size"
                    ref="secondTabFirstInput"
                    placeholder="请输入单品尺寸"
                    style="width: 205px"
                  />
                  <strong> cm</strong>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品价格" prop="price">
                  <el-input v-model="form.price" placeholder="请输入商品价格" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="周转箱尺寸" prop="containerSize">
                  <el-input
                    v-model="form.containerSize"
                    placeholder="请输入周转箱尺寸"
                    style="width: 205px"
                  />
                  <strong> cm</strong>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="颜色" prop="colorId">
                  <!-- <treeselect v-model="form.colorId" :options="colorOptions" :show-count="true" placeholder="请选择颜色"
                    @input="autoFillModel" :disable-branch-nodes="true" /> -->
                  <el-input
                    v-model="form.colorId"
                    placeholder="请输入颜色"
                    @input="autoFillModel"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="包装尺寸" prop="packageSize">
                  <el-input
                    v-model="form.packageSize"
                    placeholder="请输入包装尺寸"
                    style="width: 205px"
                  />
                  <strong> cm</strong>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="交货周期" prop="leadTime">
                  <el-input
                    v-model="form.leadTime"
                    placeholder="请输入交货周期"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="单品重量" prop="packageWeight">
                  <span slot="label"
                    >单品重量
                    <el-tooltip class="item" effect="dark" placement="right">
                      <div slot="content">带包装</div>
                      <i class="el-icon-warning-outline"></i>
                    </el-tooltip>
                  </span>
                  <el-input
                    v-model="form.packageWeight"
                    placeholder="请输入包装重量"
                    style="width: 205px"
                  />
                  <strong> kg</strong>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商" prop="vendorId">
                  <el-select
                    v-model="form.vendorId"
                    filterable
                    placeholder="请选择"
                    :style="{ width: '230px' }"
                  >
                    <el-option
                      v-for="item in vendorList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="周转箱重量" prop="turnoverBoxWeight">
                  <el-input
                    v-model="form.turnoverBoxWeight"
                    placeholder="周转箱重量"
                    style="width: 205px"
                  />
                  <strong> kg</strong>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="商品成本" prop="cost">
                  <el-input v-model="form.cost" placeholder="请输入商品成本" />
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="装箱数" prop="boxSize">
                  <el-input
                    v-model="form.boxSize"
                    placeholder="请输入装箱数"
                    required
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品重量" prop="productWeight">
                  <span slot="label"
                    >产品重量
                    <el-tooltip class="item" effect="dark" placement="right">
                      <div slot="content">不带包装</div>
                      <i class="el-icon-warning-outline"></i>
                    </el-tooltip>
                  </span>
                  <el-input
                    v-model="form.productWeight"
                    placeholder="请输入商品重量"
                    style="width: 205px"
                  />
                  <strong> kg</strong>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品材质" prop="productMaterial">
                  <el-input
                    v-model="form.productMaterial"
                    placeholder="请输入商品材质"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="包材" prop="packMaterial">
                  <el-input
                    v-model="form.packMaterial"
                    placeholder="请输入包材"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 质检信息页面 -->
          <el-tab-pane label="质检信息" name="quality">
            <el-form-item label="默认质检方式" prop="inspectionMethod">
              <el-radio-group v-model="form.inspectionMethod">
                <el-radio :label="0">抽检</el-radio>
                <el-radio :label="1">全检</el-radio>
                <el-radio :label="2">免检</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="模板" prop="templateId">
              <el-select
                v-model="form.templateId"
                placeholder="请选择模板"
                clearable
                @change="handleTemplateChange"
              >
                <el-option
                  v-for="item in templateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="自定义" prop="customQualityCheck">
              <el-table
                :data="form.customQualityCheck"
                class="full-width-table"
                border
              >
                <el-table-column
                  label="质检项（最多30项）"
                  prop="checkItem"
                  min-width="200"
                >
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="'customQualityCheck.' + $index + '.checkItem'"
                    >
                      <el-input
                        v-model="row.checkItem"
                        placeholder="质检项"
                        ref="qualityTabFirstInput"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="质检内容"
                  prop="checkContent"
                  min-width="400"
                >
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="'customQualityCheck.' + $index + '.checkContent'"
                    >
                      <el-input
                        type="textarea"
                        v-model="row.checkContent"
                        placeholder="质检内容"
                        :rows="1"
                        :autosize="{ minRows: 1, maxRows: 4 }"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template #default="{ $index }">
                    <el-button
                      type="text"
                      @click="removeQualityCheckItem($index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <el-button
                type="primary"
                icon="el-icon-plus"
                @click="addQualityCheckItem"
                :disabled="form.customQualityCheck.length >= 30"
                style="margin-top: 10px"
              >
                添加质检项
              </el-button>
            </el-form-item>
            <el-form-item label="上传图片" prop="images">
              <image-upload
                ref="qualityImageUpload"
                :auto-upload="false"
                v-model="form.images"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 修改后的弹窗底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="nextStep" v-if="activeName == 'first'"
          >下一步</el-button
        >

        <template v-else-if="activeName == 'second'">
          <el-button type="primary" @click="previousStep">上一步</el-button>
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </template>

        <template v-else-if="activeName == 'quality'">
          <el-button type="primary" @click="previousStep">上一步</el-button>
          <el-button type="primary" v-if="!viewMode" @click="submitForm"
            >确 定</el-button
          >
        </template>

        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看产品" :visible.sync="viewDialogVisible" width="80%">
      <!-- 搜索区域：按配对时间筛选 -->
      <div style="margin-bottom: 20px">
        <el-form inline>
          <el-form-item label="配对时间">
            <el-date-picker
              v-model="searchPairTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleView"
            >
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary" @click="handleView">搜索</el-button>
          </el-form-item> -->
        </el-form>
      </div>
      <el-table :data="viewData" border :span-method="tableSpanMethod">
        <!-- <el-table-column prop="pairId" label="Pair ID"></el-table-column> -->
        <el-table-column prop="itemSku" label="Walmart SKU"></el-table-column>
        <!-- <el-table-column prop="productId" label="Product ID"></el-table-column> -->
        <el-table-column prop="head" label="产品负责人"></el-table-column>
        <!-- <el-table-column prop="responsibleTime" label="Responsible Time"></el-table-column> -->
        <el-table-column prop="saleHead" label="销售负责人"></el-table-column>
        <!-- <el-table-column prop="saleResponsibleTime" label="Sale Responsible Time"></el-table-column> -->
        <!-- <el-table-column prop="deleteStatus" label="Delete Status"></el-table-column> -->
        <!-- <el-table-column prop="createTime" label="Create Time"></el-table-column> -->
        <!-- <el-table-column prop="updateTime" label="Update Time"></el-table-column> -->
        <el-table-column prop="gtin" label="GTIN"></el-table-column>
        <el-table-column prop="shopName" label="店铺名称"></el-table-column>
        <!-- <el-table-column prop="authId" label="Auth ID"></el-table-column> -->
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProducts,
  getProducts,
  addProducts,
  updateProducts,
  productTreeSelect,
  oemTreeSelect,
  productsSkuName,
  selectColorId,
  selectBrand,
  disableProducts,
  enableProducts,
  importProductExcel,
} from "@/api/commodity/products";

import { getPairView } from "@/api/walmart/items";

import {
  listTemplate,
  getTemplate,
  listTemplates,
} from "@/api/commodity/template";

import { listVendor, listProductVendor } from "@/api/commodity/vendor";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Products",
  dicts: ["sys_normal_disable", "sys_product_attribute"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 分类管理树选项
      productsOptions: [],
      //oem分类
      oemOptions: [],
      //颜色分类
      colorOptions: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品管理表格数据
      productsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 供应商下拉框
      vendorList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        catesId: null,
      },
      form: {
        // 其他需要的属性
        id: null,
        catesId: null,
        brandId: null,
        name: null,
        proNo: null,
        names: null,
        model: null,
        oem: null,
        sort: 1,
        sku: null,
        desc: null,
        remark: null,
        status: "0",
        imgName: [],
        productRemarks: null,
        second: null,
        price: null,
        containerSize: null,
        colorId: null,
        packageSize: null,
        templateId: null,
        leadTime: null,
        packageWeight: null,
        vendorId: null,
        turnoverBoxWeight: null,
        boxSize: null,
        productWeight: null,
        productMaterial: null,
        packMaterial: null,
        inspectionMethod: 0,
        customQualityCheck: [{ checkItem: "", checkContent: "" }], // 重置时添加一项
        images: [],
        size: null,
        attributes: ["0"], // 默认选中“带电”
        packingList: "",
        flag: 0, // 默认为单个产品
        productRemarksImgName: [], // 备注图片
      },
      // 表单校验
      rules: {
        names: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        brandId: [{ required: true, message: "请选择品牌", trigger: "change" }],
        model: [{ required: true, message: "请输入规格型号", trigger: "blur" }],
        desc: [{ required: true, message: "请输入产品介绍", trigger: "blur" }],
        catesId: [{ required: true, message: "请选择分类", trigger: "change" }],
        oem: [{ required: true, message: "请选择OEM", trigger: "change" }],
        packingList: [
          { required: true, message: "请输入包装清单", trigger: "blur" },
        ],
        attributes: [
          { required: true, message: "请选择必选属性", trigger: "blur" },
        ],
        size: [
          { required: true, message: "请输入单品尺寸", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入单品尺寸"));
              } else {
                const pattern =
                  /^(\d+(\.\d+)?\s*)\*\s*(\d+(\.\d+)?\s*)\*\s*(\d+(\.\d+)?)$/;
                if (!pattern.test(value)) {
                  callback(new Error("请输入正确的尺寸格式（长度*宽度*高度）"));
                } else {
                  callback();
                }
              }
            },
            trigger: "blur",
          },
        ],
        productWeight: [
          { required: true, message: "请输入产品重量", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入产品重量"));
              } else if (isNaN(value) || Number(value) <= 0) {
                callback(new Error("请输入有效的数字作为产品重量"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        packageWeight: [
          { required: true, message: "请输入单品重量", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入单品重量"));
              } else if (isNaN(value) || Number(value) <= 0) {
                callback(new Error("请输入有效的数字作为单品重量"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        vendorId: [
          { required: true, message: "请选择供应商", trigger: "change" },
        ],
        colorId: [{ required: true, message: "请选择颜色", trigger: "change" }],
        price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入商品价格"));
              } else if (isNaN(value) || Number(value) <= 0) {
                callback(new Error("请输入有效的数字作为商品价格"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        turnoverBoxWeight: [
          { required: true, message: "请输入周转箱重量", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入周转箱重量"));
              } else if (isNaN(value) || Number(value) <= 0) {
                callback(new Error("请输入有效的数字作为周转箱重量"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        boxSize: [
          { required: true, message: "请输入装箱数", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              // 如果不是数字，或数值 <= 0，则提示错误
              if (isNaN(value) || Number(value) <= 0) {
                callback(new Error("请输入有效的数字作为装箱数"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        containerSize: [
          { required: true, message: "请输入周转箱尺寸", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入周转箱尺寸"));
              } else {
                const pattern =
                  /^(\d+(\.\d+)?\s*)\*\s*(\d+(\.\d+)?\s*)\*\s*(\d+(\.\d+)?)$/;
                if (!pattern.test(value)) {
                  callback(new Error("请输入正确的尺寸格式（长度*宽度*高度）"));
                } else {
                  callback();
                }
              }
            },
            trigger: "blur",
          },
        ],
        packageSize: [
          { required: true, message: "请输入包装尺寸", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请输入包装尺寸"));
              } else {
                const pattern =
                  /^(\d+(\.\d+)?\s*)\*\s*(\d+(\.\d+)?\s*)\*\s*(\d+(\.\d+)?)$/;
                if (!pattern.test(value)) {
                  callback(new Error("请输入正确的尺寸格式（长度*宽度*高度）"));
                } else {
                  callback();
                }
              }
            },
            trigger: "blur",
          },
        ],
      },
      //产品名称
      productsName: null,
      defaultProps: {
        children: "children",
        label: "label",
      },
      //切换
      activeName: "first",
      /** 是添加为true 是修改为false */
      insertUpdate: "",
      /** 品牌数据 */
      brandList: [],
      QRCode: [],
      brandForm: {},
      templateOptions: [],
      // 新增组合产品相关的属性：
      isCombination: false, // 是否为组合产品模式
      selectedProductsForCombo: [], // 存放组合产品中选中的单品数据（并附加数量字段 comboQty ）
      selectedProducts: [], // 全局保存选中的产品
      selectedProductIds: [], // 全局选中的id
      viewDialogVisible: false, // 控制查看弹窗的显示与隐藏
      viewData: [], // 存放要查看的产品数据
      // 搜索条件：存储选择的配对时间（日期范围）
      searchPairTime: [],
      id: null, //查看配对的walmart链接信息的全局搜索id
      viewMode: false, // 默认非查看模式
      // 需要根据品牌禁用的配置
      brandRules: {
        // INSMART相关品牌
        INSMART: {
          disabledCategories: [1, 2, 6, 9, 12], // 汽配类及子类、工具和家庭装修类、庭院草坪花园类
          disabledOem: [2, 9, 12], // CC、TH、PL
        },
        // PECHAM相关品牌
        PECHAM: {
          disabledCategories: [
            4, 3, 8, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21,
          ], // 个护类等
          disabledOem: [3, 7, 8, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21], // WF、HG等
        },
      },
      // 处理后用于显示的数据
      processedProductsOptions: [],
      processedOemOptions: [],
      lastAddFormData: null, // 存储新增操作的表单数据
    };
  },
  created() {
    this.getList();
    this.getProductTree();
    this.getoemTree();
    this.getSelectColor();
    this.getSelectBrand();
  },
  watch: {
    // 根据名称筛选部门树
    productsName(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {
    // 页面加载时确保至少有一个质检项
    if (this.form.customQualityCheck.length === 0) {
      this.form.customQualityCheck.push({ checkItem: "", checkContent: "" });
    }
  },
  methods: {
    // 根据下拉菜单的选择进行操作
    handleCommand(row, command) {
      if (command === "handleUpdate") {
        this.viewMode = false; // 修改模式
        this.handleUpdate(row);
      } else if (command === "handleView") {
        this.handleView(row);
      } else if (command === "view") {
        this.viewMode = true; // 查看模式，后续在弹窗中隐藏“确定”按钮
        this.handleUpdate(row);
      }
    },
    getVendorList() {
      listProductVendor().then((response) => {
        this.vendorList = response.rows;
      });
    },
    /** 查询产品管理列表 */
    getList() {
      this.loading = true;
      listProducts(this.queryParams).then((response) => {
        this.productsList = response.rows;
        this.total = response.total;
        // 在下一次渲染时，恢复选中的状态
        this.$nextTick(() => {
          this.productsList.forEach((row) => {
            if (this.selectedProductIds.includes(row.id)) {
              this.$refs.table.toggleRowSelection(row, true);
            }
          });
        });
        this.loading = false;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.catesId = data.id;
      this.handleQuery();
    },
    // 添加到methods中
    handleDialogClose() {
      // 调用与取消按钮相同的逻辑
      this.cancel();
    },
    // 取消按钮
    cancel() {
      // 如果是新增操作，保存表单数据
      if (this.insertUpdate) {
        this.lastAddFormData = JSON.parse(JSON.stringify(this.form));
      } else {
        // 如果不是新增操作，清除保存的表单数据
        this.lastAddFormData = null;
      }

      this.open = false;

      // 只有在非新增操作时才重置表单
      if (!this.insertUpdate) {
        this.reset();
      }

      this.viewMode = false;
    },
    // 表单重置
    reset() {
      // 保留响应式对象，更新其属性
      Object.assign(this.form, {
        id: null,
        catesId: null,
        brandId: null,
        name: null,
        proNo: null,
        names: null,
        model: null,
        oem: null,
        sort: 1,
        sku: null,
        desc: null,
        remark: null,
        status: "0",
        imgName: [],
        productRemarks: null,
        second: null,
        price: null,
        containerSize: null,
        colorId: null,
        packageSize: null,
        templateId: null,
        leadTime: null,
        packageWeight: null,
        vendorId: null,
        turnoverBoxWeight: null,
        boxSize: null,
        productWeight: null,
        productMaterial: null,
        packMaterial: null,
        inspectionMethod: 0,
        customQualityCheck: [{ checkItem: "", checkContent: "" }], // 重置时添加一项
        images: [],
        size: null,
        attributes: ["0"], // 默认选中“带电”
        packingList: "",
        flag: 0,
        productRemarksImgName: [], // 备注图片
      });
      // 新增：重置组合状态
      this.isCombination = false;
      this.selectedProductsForCombo = [];
      this.resetForm("form");
    },

    /** 查询部门下拉树结构 */
    getProductTree() {
      productTreeSelect().then((response) => {
        this.productsOptions = response.data;
      });
    },
    /**查看orm下拉树结构 */
    getoemTree() {
      oemTreeSelect().then((response) => {
        this.oemOptions = response.data;
      });
    },
    /**查看颜色下拉数结构 */
    getSelectColor() {
      selectColorId().then((response) => {
        this.colorOptions = response.data;
      });
    },
    getSelectBrand() {
      selectBrand().then((response) => {
        this.brandList = response.data;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    // handleSelectionChange(selection) {
    //   // 获取当前页所有的 id
    //   const currentPageIds = this.productsList.map(item => item.id);

    //   // 从全局选中列表中移除当前页中已取消选中的项
    //   this.selectedProducts = this.selectedProducts.filter(item => {
    //     // 如果 item 不在当前页，则保留；如果在当前页，则只有当它依然被选中时才保留
    //     return !currentPageIds.includes(item.id) || selection.some(s => s.id === item.id);
    //   });

    //   // 将当前页选中的项添加到全局列表（去重）
    //   selection.forEach(item => {
    //     if (!this.selectedProducts.find(x => x.id === item.id)) {
    //       this.selectedProducts.push(item);
    //     }
    //   });
    //   console.log(JSON.stringify(this.selectedProducts.length));

    //   // 更新全局选中 id 数组
    //   this.selectedProductIds = this.selectedProducts.map(item => item.id);
    //   // 更新其他状态，如 QRCode、ids、single、multiple
    //   this.QRCode = [...this.selectedProducts];
    //   this.ids = selection.map(item => item.id);
    //   this.single = selection.length !== 1;
    //   this.multiple = !selection.length;
    // },
    handleSelectionChange(selection) {
      this.selectedProducts = selection; // 直接使用 selection
      this.selectedProductIds = selection.map((item) => item.id);
      this.QRCode = [...selection];
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 判断一个品牌是否是另一个品牌的子品牌
    isSubBrand(parentId, childId) {
      // 遍历品牌树，查找父品牌ID
      const findBrand = (brandList, parentId) => {
        for (let brand of brandList) {
          if (brand.id === parentId) {
            return brand;
          }
          if (brand.children) {
            const found = findBrand(brand.children, parentId);
            if (found) return found;
          }
        }
        return null;
      };

      // 获取父品牌信息
      const parentBrand = findBrand(this.brandList, parentId);
      if (!parentBrand) return false;

      // 如果父品牌没有子品牌，则直接判断是否为同一品牌
      if (!parentBrand.children) return parentId === childId;

      // 检查子品牌是否在该父品牌树中
      const isChild = parentBrand.children.some(
        (child) => child.id === childId
      );
      return isChild || parentId === childId; // 如果是自己也返回 true
    },

    // 新增：组合产品按钮点击事件
    async handleCombine() {
      if (this.QRCode.length < 2) {
        this.$message.error("请至少选择两个产品进行组合");
        return;
      }
      // 检查是否有停用的产品（假设停用状态是'2'）
      const disabledProducts = this.QRCode.filter(
        (item) => item.status === "1"
      );
      if (disabledProducts.length > 0) {
        this.$message.warning(
          `选中的产品中有停用的产品：${disabledProducts
            .map((item) => item.name)
            .join(", ")}。请先启用这些产品后再进行组合。`
        );
        return;
      }
      // 检查是否已经选择了组合产品（即 flag = 1 的产品）
      const comboProducts = this.QRCode.filter((item) => item.flag == 1);
      if (comboProducts.length > 0) {
        this.$message.warning(
          `选中的产品中包含已有的组合产品：${comboProducts
            .map((item) => item.name)
            .join(", ")}。无法将组合产品再次加入组合。`
        );
        return;
      }

      // 检查是否所有选中的产品属于同一个品牌（包括父品牌和子品牌）
      const brandIds = this.QRCode.map((item) => item.brandId);

      // 获取第一个勾选品牌的父品牌ID
      const firstBrandId = brandIds[0];

      // 遍历其他勾选的品牌，检查是否属于同一个品牌树下
      for (let i = 1; i < brandIds.length; i++) {
        const currentBrandId = brandIds[i];

        // 检查是否是同一父品牌或者子品牌
        if (
          !this.isSubBrand(firstBrandId, currentBrandId) &&
          !this.isSubBrand(currentBrandId, firstBrandId)
        ) {
          this.$message.warning("选中的产品属于不同的品牌，不能进行组合。");
          return;
        }
      }

      // 重置表单，复用新增弹窗
      this.reset();
      this.insertUpdate = true;
      this.activeName = "first";
      this.open = true;
      this.title = "新增组合产品";
      this.getVendorList(); // 获取供应商下拉框
      this.isCombination = true;
      // 将选中的产品复制到组合产品列表，并默认数量为1
      this.selectedProductsForCombo = this.QRCode.map((item) => ({
        ...item,
        comboQty: 1,
      }));
      // 加载质检模板
      const templateResponse = await listTemplate();
      // 处理响应数据以填充下拉选项
      this.templateOptions = templateResponse.rows.map((template) => ({
        value: template.templateId,
        label: template.templateName,
      }));
    },
    // 返回表单的默认数据
    getDefaultForm() {
      return {
        id: null,
        catesId: null,
        brandId: null,
        name: null,
        proNo: null,
        names: null,
        model: null,
        oem: null,
        sort: 1,
        sku: null,
        desc: null,
        remark: null,
        status: "0",
        imgName: [],
        productRemarks: null,
        second: null,
        price: null,
        containerSize: null,
        colorId: null,
        packageSize: null,
        templateId: null,
        leadTime: null,
        packageWeight: null,
        vendorId: null,
        turnoverBoxWeight: null,
        boxSize: null,
        productWeight: null,
        productMaterial: null,
        packMaterial: null,
        inspectionMethod: 0,
        customQualityCheck: [{ checkItem: "", checkContent: "" }],
        images: [],
        size: null,
        attributes: ["0"],
        packingList: "",
        flag: 0,
        variantOperation: false,
        productRemarksImgName: [], // 备注图片
      };
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 检查是否有之前保存的新增表单数据
      if (this.lastAddFormData) {
        // 恢复保存的表单数据
        this.form = JSON.parse(JSON.stringify(this.lastAddFormData));
      } else {
        // 重新赋值整个表单对象，确保没有多余属性残留
        this.form = this.getDefaultForm();
      }
      this.getVendorList(); // 获取供应商下拉框
      this.loading = true; // 显示加载指示器
      listTemplate()
        .then((response) => {
          // 处理响应数据以填充下拉选项
          this.templateOptions = response.rows.map((template) => ({
            value: template.templateId,
            label: template.templateName,
          }));
          this.activeName = "first";
          this.insertUpdate = true;
          this.open = true;
          this.title = "添加产品";
        })
        .catch((error) => {
          console.error("Failed to load quality templates:", error);
          this.$message.error("加载质检模板数据失败");
        })
        .finally(() => {
          this.loading = false; // 隐藏加载指示器
        });
    },
    // 修改按钮操作
    async handleUpdate(row) {
      this.form = this.getDefaultForm();
      this.getVendorList(); // 获取供应商下拉框
      if (row.flag == 1) {
        this.$message.warning("组合产品不能修改!");
        return;
      }
      try {
        // 加载质检模板
        const templateResponse = await listTemplates();
        // 处理响应数据以填充下拉选项
        this.templateOptions = templateResponse.rows.map((template) => ({
          value: template.templateId,
          label: template.templateName,
        }));
        this.activeName = "first";
        this.insertUpdate = false;

        // 获取ID
        const id = row.id || this.ids;

        // 加载产品数据
        const productResponse = await getProducts(id);

        // 从产品名称中提取出前部分（去除空格后部分）
        const name = productResponse.data.name.split(" ")[0];

        // 更新表单数据，确保保留所有属性
        this.form = { ...productResponse.data, names: name };

        // 调用封装的函数来填充类目和OEM
        this.fillOptions(this.productsOptions, this.oemOptions);

        // 确保所有需要的属性都存在
        this.ensureFormDefaults();

        // 显示弹窗
        this.open = true;
        this.title = "修改产品";
      } catch (error) {
        console.error("Error in handleUpdate:", error);
        this.$message.error("加载数据失败，请稍后再试！");
      } finally {
        this.loading = false; // 隐藏加载指示器
      }
    },
    // 变体按钮逻辑操作
    async handleVariant() {
      // 如果没有选中或选中多个，提示错误（与修改按钮的禁用逻辑一致）
      if (this.QRCode.length !== 1) {
        this.$message.warning("请先选择一个产品进行变体操作");
        return;
      }

      // 取选中的产品（与修改逻辑类似）
      const row = this.QRCode[0];

      // 新增校验逻辑：判断是否已存在变体标识（包含-号）
      if (row.sku && row.sku.includes("-")) {
        // 核心校验逻辑
        this.$message.warning(
          "该SKU(" + row.sku + ")已是变体产品，无法再次变体！"
        );
        return;
      }
      // 重置表单并加载供应商数据
      this.reset();
      this.getVendorList();

      // 如果产品为组合产品，则不允许操作（保持与修改按钮一致的判断）
      if (row.flag == 1) {
        this.$message.warning("组合产品不能修改!");
        return;
      }

      try {
        // 加载质检模板
        const templateResponse = await listTemplate();
        this.templateOptions = templateResponse.rows.map((template) => ({
          value: template.templateId,
          label: template.templateName,
        }));

        this.activeName = "first";
        this.insertUpdate = false; // 修改模式
        // 获取产品ID，优先使用 row.id
        const id = row.id || this.ids;
        // 获取产品详细数据
        const productResponse = await getProducts(id);
        // 从产品名称中提取前半部分（示例逻辑）
        const name = productResponse.data.name.split(" ")[0];
        // 将回显数据赋值到 form，同时增加变体操作的标识（例如 variantOperation 字段）
        // 填充一下类目和OEM
        // 调用封装的函数来填充类目和OEM
        this.fillOptions(this.productsOptions, this.oemOptions);

        this.form = {
          ...productResponse.data,
          names: name,
          variantOperation: true,
        };
        this.ensureFormDefaults();
        // 显示弹窗，并设置标题为“变体产品”
        this.open = true;
        this.title = "变体产品";
      } catch (error) {
        console.error("Error in handleVariant:", error);
        this.$message.error("加载数据失败，请稍后再试！");
      } finally {
        this.loading = false;
      }
    },
    // 封装函数：填充类目和OEM
    fillOptions(productsOptions, oemOptions) {
      this.processedProductsOptions = productsOptions;
      this.processedOemOptions = oemOptions;
    },

    // 确保表单的默认值
    ensureFormDefaults() {
      if (!this.form.customQualityCheck) {
        this.form.customQualityCheck = [{ checkItem: "", checkContent: "" }];
      }
      if (!this.form.images) {
        this.form.images = [];
      }
      if (!this.form.imgName) {
        this.form.imgName = [];
      }
      if (!this.form.productRemarksImgName) {
        this.form.productRemarksImgName = [];
      }
    },

    // 自定义顺序验证方法
    validateFieldsSequentially(fields) {
      return new Promise((resolve, reject) => {
        const validateField = (index) => {
          if (index >= fields.length) {
            resolve();
            return;
          }
          let field = fields[index];
          this.$refs.form.validateField(field, (errorMessage) => {
            if (errorMessage) {
              reject(errorMessage);
            } else {
              validateField(index + 1);
            }
          });
        };
        validateField(0);
      });
    },

    nextStep() {
      if (this.activeName == "first") {
        let fields = [
          "names",
          "brandId",
          "model",
          "desc",
          "catesId",
          "oem",
          "packingList",
          "attributes",
        ];
        this.validateFieldsSequentially(fields)
          .then(() => {
            this.activeName = "second";
          })
          .catch((errorMessage) => {
            this.$message.error(errorMessage);
          });
      } else if (this.activeName == "second") {
        let fields = [
          "size",
          "productWeight",
          "packageWeight",
          "vendorId",
          "colorId",
          "price",
          "turnoverBoxWeight",
          "containerSize",
          "packageSize",
          "boxSize",
        ];
        this.validateFieldsSequentially(fields)
          .then(() => {
            this.activeName = "quality";
          })
          .catch((errorMessage) => {
            this.$message.error(errorMessage);
          });
      }
    },
    previousStep() {
      if (this.activeName == "second") {
        this.activeName = "first";
      } else if (this.activeName == "quality") {
        this.activeName = "second";
      }
    },
    /** 提交按钮 */
    submitForm() {
      // 验证至少选择一个质检模板或至少有一个自定义质检项
      if (!this.validateQualityCheckSelection()) {
        this.$message.error("请选择至少一个质检模板或添加至少一个自定义质检项");
        return;
      }

      this.$refs.form.validate(async (valid, invalidFields) => {
        if (valid) {
          // 新增：如果为组合产品，先根据各产品数量生成组合SKU
          if (this.isCombination) {
            let comboArr = [];
            for (let item of this.selectedProductsForCombo) {
              if (!item.comboQty || item.comboQty < 1) {
                this.$message.error("请为产品 " + item.sku + " 填写正确的数量");
                return;
              }
              if (item.comboQty === 1) {
                comboArr.push(item.sku);
              } else {
                comboArr.push(item.sku + "*" + item.comboQty);
              }
            }
            // 生成组合SKU，例如 "公模10001+公模10002*6+公模10003*20"
            this.form.sku = comboArr.join("+");
            this.form.isCombination = this.isCombination; // 区分新增产品时是否是组合新增产品
            this.form.flag = 1; //表示为组合产品
          }
          try {
            // 手动触发图片上传
            await this.$refs.productImageUpload.submitUpload();
            await this.$refs.qualityImageUpload.submitUpload();
            await this.$refs.remarkImageUpload.submitUpload();

            // 提交表单逻辑
            if (this.form.id != null) {
              updateProducts(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.lastAddFormData = null; // 清除保存的数据
                this.getList();
              });
            } else {
              addProducts(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.lastAddFormData = null; // 清除保存的数据
                this.getList();
              });
            }
          } catch (error) {
            this.$message.error("图片上传失败，请重试");
          }
        } else {
          const firstErrorField = Object.keys(invalidFields)[0];
          const errorMessage = invalidFields[firstErrorField][0].message;
          this.$message.error(errorMessage);
        }
      });
    },

    /** 删除按钮操作 */
    // handleDelete(row) {
    //   const ids = row.id || this.ids;
    //   this.$modal
    //     .confirm('是否确认删除产品管理编号为"' + ids + '"的数据项？')
    //     .then(function () {
    //       return delProducts(ids);
    //     })
    //     .then(() => {
    //       this.getList();
    //       this.$modal.msgSuccess("删除成功");
    //     })
    //     .catch(() => { });
    // },
    // 停用按钮点击事件
    handleDisable() {
      const ids = this.ids; // 假设这儿获取了选中的产品ID
      if (ids.length === 0) {
        this.$message.warning("请至少选择一个产品进行停用");
        return;
      }
      // 假设你有API接口来停用产品
      this.$modal.confirm("确认停用选中的产品吗？").then(() => {
        // 调用API进行停用操作
        disableProducts(ids).then(() => {
          this.$message.success("产品已停用");
          this.getList(); // 刷新产品列表
        });
      });
    },

    // 启用按钮点击事件
    handleEnable() {
      const ids = this.ids; // 假设这儿获取了选中的产品ID
      if (ids.length === 0) {
        this.$message.warning("请至少选择一个产品进行启用");
        return;
      }
      // 假设你有API接口来启用产品
      this.$modal.confirm("确认启用选中的产品吗？").then(() => {
        // 调用API进行启用操作
        enableProducts(ids).then(() => {
          this.$message.success("产品已启用");
          this.getList(); // 刷新产品列表
        });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "commodity/products/export",
        {
          ...this.queryParams,
        },
        `products_${new Date().getTime()}.xlsx`
      );
    },

    // 品牌选择变化时触发
    handleChange() {
      this.handleBrandChange();
    },
    /**规格型号，监听 */
    autoFillModel() {
      let colorId = this.form.colorId || "";
      let brandId = Number(this.form.brandId || 0);
      let brandName = "";
      let colorName = "";

      // 获取品牌名称
      if (brandId > 0) {
        let brandOption = this.brandList.find((item) => item.id === brandId);
        if (brandOption) {
          brandName = brandOption.label || brandOption.name || "";
        }
      }

      // 获取颜色名称
      if (colorId) {
        // selectColorByIds(colorId).then((response) => {
        // colorName = response.data.colorName || '';
        this.setFormName(colorId, brandName);
        // });
      } else {
        this.setFormName("", brandName);
      }
    },
    // 修改 setFormName 方法
    setFormName(colorName = "", brandName = "") {
      this.form.name =
        `${this.form.names || ""}` +
        " " +
        `${this.form.model || ""}` +
        " " +
        colorName +
        " " +
        brandName;
    },

    autoFillOEM() {
      if (this.form.oem != null) {
        productsSkuName(this.form.oem).then((response) => {
          console.log(this.form.oem);

          // 添加产品的时候才允许修改产品sku
          if (this.insertUpdate == true) {
            this.form.sku = response.msg;
          }
        });
      }
    },

    handleQueryCode() {
      localStorage.setItem("QRCode", JSON.stringify(this.QRCode));
      this.$router.push("/qrCode/index");
    },

    // 质检信息相关方法
    // 添加质检项
    addQualityCheckItem() {
      if (this.form.customQualityCheck.length < 30) {
        this.form.customQualityCheck.push({ checkItem: "", checkContent: "" });
      } else {
        this.$message.warning("最多只能添加30项质检项");
      }
    },
    // 删除质检项
    removeQualityCheckItem(index) {
      if (this.form.customQualityCheck.length === 1) {
        this.$message.warning("至少需要保留一个质检项");
      } else {
        this.form.customQualityCheck.splice(index, 1);
      }
    },
    // 验证质检项
    validateQualityCheckSelection() {
      return (
        this.form.templateId ||
        this.form.customQualityCheck.some(
          (item) => item.checkItem && item.checkContent
        )
      );
    },
    //质检模板选择触发事件
    async handleTemplateChange(templateId) {
      if (templateId) {
        const response = await this.fetchTemplateData(templateId);

        if (response && response.data && response.data.templateImagePaths) {
          this.form.images = [...response.data.templateImagePaths]; // 展开并直接赋值
        }
      }
    },

    fetchTemplateData(templateId) {
      return getTemplate(templateId).then((response) => {
        return response;
      });
    },
    // 触发文件选择窗口
    triggerProductFileInput() {
      this.$refs.productFileInput.click();
    },
    //导入产品表格
    handleProductFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      const formData = new FormData();
      formData.append("file", file);

      importProductExcel(formData)
        .then((response) => {
          this.$message.success("表格文件上传成功！");
          this.getList();
          this.resetFileInput(); // ✅ 上传成功后重置
        })
        .catch((error) => {
          this.resetProductFileInput(); // ✅ 上传失败后重置
        });
    },
    // ✅ 重置文件选择框（确保可以再次选择相同文件）
    resetProductFileInput() {
      this.$refs.productFileInput.value = ""; // 清空 input[type=file] 的值
    },
    // 查看按钮点击事件
    handleView(row) {
      // 构造查询参数对象
      const params = {};
      if (row && row.id) {
        this.id = row.id;
      }
      params.id = this.id;
      if (this.searchPairTime && this.searchPairTime.length === 2) {
        // 可根据后端要求调整时间格式，这里直接传 Date 对象或字符串
        params.startTime = this.formatDate(this.searchPairTime[0]);
        params.endTime = this.formatDate(this.searchPairTime[1]);
      }
      // 调用接口时传递参数，假设 getPairView 接口支持查询参数（实际接口参数请根据后端文档调整）
      getPairView(params)
        .then((response) => {
          // 后端返回符合条件的数据赋值给 viewData
          this.viewData = response.data;
          this.viewDialogVisible = true;
        })
        .catch((error) => {
          this.$message.error("获取数据失败，请重试");
          console.error(error);
        });
    },
    // span-method 用于对 authId 列实现合并效果
    tableSpanMethod({ row, column, rowIndex }) {
      if (column.property === "authId") {
        // 如果当前行的 authId 与上一行相同，则返回 [0, 0]，使其合并到上一行
        if (
          rowIndex > 0 &&
          this.viewData[rowIndex].authId === this.viewData[rowIndex - 1].authId
        ) {
          return [0, 0];
        }
        // 计算后续连续相同 authId 的行数
        let rowspan = 1;
        for (let i = rowIndex + 1; i < this.viewData.length; i++) {
          if (this.viewData[i].authId === row.authId) {
            rowspan++;
          } else {
            break;
          }
        }
        return [rowspan, 1];
      }
    },
    // 格式化日期为 'yyyy-MM-dd' 或 'yyyy-MM-dd HH:mm:ss'
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, "0");
      const day = d.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`; // 或者返回完整时间：`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    handleBrandChange() {
      // 重置选择
      this.form.catesId = null;
      this.form.oem = null;
      this.$nextTick(() => {
        this.processOptions();
      });
    },

    // 处理选项禁用逻辑
    processOptions() {
      // 深拷贝原始选项，避免修改原始数据
      const productsClone = JSON.parse(JSON.stringify(this.productsOptions));
      const oemClone = JSON.parse(JSON.stringify(this.oemOptions));
      // 如果没有选择品牌，则不做处理
      if (!this.form.brandId) {
        this.productsOptions = productsClone;
        this.oemOptions = oemClone;
        return;
      }

      // 获取当前品牌
      let currentBrand = "";
      if (this.form.brandId) {
        // 查找选中的品牌值
        const brandValue = this.findBrandValueById(this.form.brandId);

        if (brandValue && brandValue.includes("INSMART")) {
          currentBrand = "INSMART";
        } else if (brandValue && brandValue.includes("PECHAM")) {
          currentBrand = "PECHAM";
        }
      }

      if (currentBrand && this.brandRules[currentBrand]) {
        const rules = this.brandRules[currentBrand];

        // 处理产品类型禁用
        if (productsClone.length > 0 && productsClone[0].children) {
          this.disableCategories(
            productsClone[0].children,
            rules.disabledCategories
          );
        }

        // 处理OEM禁用
        for (const oemGroup of oemClone) {
          if (oemGroup.children) {
            this.disableOemOptions(oemGroup.children, rules.disabledOem);
          }
        }
      }

      // 只更新处理后的数据，不修改原始数据
      this.processedProductsOptions = productsClone;
      this.processedOemOptions = oemClone;
    },

    // 递归禁用产品类别
    disableCategories(categories, disabledIds) {
      for (const category of categories) {
        if (disabledIds.includes(category.id)) {
          category.isDisabled = true;
        }

        if (category.children && category.children.length > 0) {
          this.disableCategories(category.children, disabledIds);
        }
      }
    },

    // 禁用OEM选项
    disableOemOptions(options, disabledIds) {
      for (const option of options) {
        if (disabledIds.includes(option.id)) {
          option.isDisabled = true;
        }
      }
    },

    // 根据ID查找品牌值
    findBrandValueById(id) {
      // 在品牌列表中查找对应的值
      for (const brand of this.brandList) {
        if (brand.id === id) {
          return brand.value;
        }

        if (brand.children) {
          for (const child of brand.children) {
            if (child.id === id) {
              return child.value;
            }
          }
        }
      }
      return null;
    },
  },
};
</script>
<style>
.full-width-table {
  width: 100%;
  max-width: 100%;
}

.el-col > .el-form-item {
  width: 100%;
  /* 确保表单项占据其父元素的全部宽度 */
}

input[aria-hidden="true"] {
  display: none !important;
}

.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner {
  box-shadow: none;
}

.image-container {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: center;
  /* 添加此行，使内容水平居中 */
}

.image-item {
  margin-right: 5px;
}

.textarea-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.textarea-container .el-textarea {
  border: none;
}

.textarea-container .el-textarea__inner {
  border: none;
  border-radius: 0;
  border-bottom: 1px solid #f0f0f0;
}

.upload-section {
  padding: 8px 12px;
  background: #fafafa;
  border-top: 1px solid #f0f0f0;
}
</style>
